import { Injectable } from '@nestjs/common';
// import { ConfigService } from '@nestjs/config';
import { History } from './history.entity';
import { Between, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { PagingResponse } from 'src/constants/common.constants';
import { AppHistoryListDto } from './dto/list.dto';
import { AddHistoryDto } from './dto/add.dto';
import dayjs from 'dayjs';
// import { PassThrough } from 'stream';
@Injectable()
export class AppHistoryService {
  private access_token: string;
  private expires_in: number;
  private timestamp: number;

  constructor(
    @InjectRepository(History)
    private readonly appHistoryRepository: Repository<History>,
  ) {}

  async findList(
    userId: string,
    params: AppHistoryListDto,
  ): Promise<PagingResponse<History>> {
    console.log('params', params);
    // console.log(
    //   this.configService.get('DATABASE_HOST'),
    //   this.configService.get('database.host'),
    //   await this.cacheManager.get('key'),
    //   await this.userRepository.findAndCount({
    //     where: {
    //       ...params.params,
    //     },
    //   }),
    // );
    console.log(
      dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
      dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
    );
    const [items, total] = await this.appHistoryRepository.findAndCount({
      skip: (params.pageNum - 1) * params.pageSize, // skip the items for the previous pages
      take: params.pageSize,
      where: {
        // ...params.params,
        userId,
        // articleName: Like(`%${params.articleName}%`),
        updatedAt: Between(
          dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
          dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss'),
        ),
      },
    });
    const { pageSize, pageNum } = params;
    return {
      records: items,
      total,
      pageSize,
      current: pageNum,
      pages: Math.ceil(total / pageSize),
    };
    // const [items] = await this.AppHistoryRepository.findAndCount({});
    // return items;
    // return await this.userRepository
    //   .createQueryBuilder()
    //   .where({ deleted: 0 })
    //   .select(['user_name', 'email'])
    //   .getMany();
    //   .find();
  }

  async findOne(id: number) {
    return await this.appHistoryRepository.findOne({
      where: {
        id,
      },
    });
  }

  async create(userId: string, history: AddHistoryDto): Promise<History> {
    const oldHistory = await this.appHistoryRepository.findOne({
      where: {
        gatherId: history.gatherId,
        articleId: history.articleId,
        userId,
      },
    });
    let progress: { index: number; duration: number } = {
      index: 0,
      duration: 0,
    };
    try {
      progress = JSON.parse(history.progress);
    } catch (error) {
      console.log('error', error);
    }
    if (oldHistory) {
      const oldDuration = oldHistory.duration;
      const newDuration = progress.duration + oldDuration;
      const newHistory = {
        ...history,
        duration: newDuration,
      };
      await this.appHistoryRepository.update(
        {
          id: oldHistory.id,
        },
        {
          duration: newDuration,
          progress: history.progress,
        },
      );
      return {
        ...oldHistory,
        ...newHistory,
      };
    }
    const data = this.appHistoryRepository.create({
      userId,
      ...history,
      duration: progress.duration,
    });
    return this.appHistoryRepository.save(data);
  }

  async remove(ids: string): Promise<void> {
    await this.appHistoryRepository.delete(ids.split(','));
  }

  /**
   * 查询某个用户的所有历史记录所消耗的时间
   * @param userId
   * @returns
   */
  async findUserProgressTime(userId: string): Promise<History[]> {
    const items = await this.appHistoryRepository.find({
      where: {
        userId,
      },
      select: ['progress', 'updatedAt'],
    });
    return items;
  }
}
